import { getTokenInfo } from '@/utils/storage'

export type Auth = {
  token: string
  refresh_token: string
}

// 个人资料 类型定义
export type Profile = {
  id: string
  photo: string
  name: string
  mobile: string
  gender: number
  birthday: string
  intro: string
}

// 个人信息 类型定义
export type User = {
  id: string
  name: string
  photo: string
  art_count: number
  follow_count: number
  fans_count: number
  like_count: number
}

// 初始数据
const initState = {
  profile: {} as Profile,
  auth: getTokenInfo(),
  user: {} as User,
}

export type UserAction =
  | { type: 'user/saveToken'; payload: Auth }
  | { type: 'user/clearToken' }
  | { type: 'user/saveUserInfo'; payload: User }
  | { type: 'user/saveProfile'; payload: Profile }
  // 利用泛型工具 Partial<> 吧属性内容转为可选 , 用于更新单个用户信息
  | { type: 'user/updateProfile'; payload: Partial<Profile> }

export function userRducer(state = initState, action: UserAction) {
  switch (action.type) {
    case 'user/saveToken':
      return { ...state, auth: action.payload }
    case 'user/clearToken':
      return { ...state, auth: {} as Auth }
    case 'user/saveUserInfo':
      return { ...state, user: action.payload }
    case 'user/saveProfile':
      return { ...state, profile: action.payload }
    case 'user/updateProfile':
      return { ...state, profile: { ...state.profile, ...action.payload } }
    default:
      return state
  }
}
